package com.duojuhe.coremodule.notice.service.impl;

import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.notice.entity.NoticeCategory;
import com.duojuhe.coremodule.notice.entity.NoticeInfo;
import com.duojuhe.coremodule.notice.mapper.NoticeCategoryMapper;
import com.duojuhe.coremodule.notice.mapper.NoticeInfoMapper;
import com.duojuhe.coremodule.notice.pojo.dto.category.*;
import com.duojuhe.coremodule.notice.service.NoticeCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class NoticeCategoryServiceImpl extends BaseService implements NoticeCategoryService {
    @Resource
    private NoticeCategoryMapper noticeCategoryMapper;
    @Resource
    private NoticeInfoMapper noticeInfoMapper;
    /**
     * 【查询所有公告分类】公告分类管理
     * @param req
     * @return
     */
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QueryNoticeCategoryPageRes>>> queryNoticeCategoryPageResList(QueryNoticeCategoryPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,createTime desc, categoryId desc");
        List<QueryNoticeCategoryPageRes> list = noticeCategoryMapper.queryNoticeCategoryPageResList(req);
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【查询所有公告分类】供前端选择公告分类
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.TENANT_ALL_DATA)
    @Override
    public ServiceResult<List<QuerySelectNoticeCategoryRes>> querySelectNormalNoticeCategoryResList(QuerySelectNoticeCategoryReq req) {
        PageHelperUtil.defaultOrderBy("sort desc,createTime desc, categoryId desc");
        List<QuerySelectNoticeCategoryRes> list = noticeCategoryMapper.querySelectNormalNoticeCategoryResList(req);
        return ServiceResult.ok(list);
    }

    /**
     * 【保存】公告分类
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveNoticeCategory(SaveNoticeCategoryReq req) {
        //分类ID
        String categoryId = UUIDUtils.getUUID32();
        //当前登录用户
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前时间
        Date date = new Date();
        NoticeCategory category = new NoticeCategory();
        category.setCategoryId(categoryId);
        category.setCategoryName(req.getCategoryName());
        category.setCreateTime(date);
        category.setUpdateTime(date);
        category.setSort(req.getSort());
        category.setCreateUserId(userTokenInfoVo.getUserId());
        category.setUpdateUserId(userTokenInfoVo.getUserId());
        category.setCreateDeptId(userTokenInfoVo.getCreateDeptId());
        category.setTenantId(userTokenInfoVo.getTenantId());
        noticeCategoryMapper.insertSelective(category);
        return ServiceResult.ok(categoryId);
    }

    /**
     * 【修改】公告分类
     * @param req
     * @return
     */
    @Override
    public ServiceResult updateNoticeCategory(UpdateNoticeCategoryReq req) {
        //分类ID
        String categoryId = req.getCategoryId();
        NoticeCategory categoryOld = noticeCategoryMapper.selectByPrimaryKey(categoryId);
        if (categoryOld==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录用户
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前时间
        Date date = new Date();
        NoticeCategory category = new NoticeCategory();
        category.setCategoryId(categoryId);
        category.setCategoryName(req.getCategoryName());
        category.setUpdateTime(date);
        category.setSort(req.getSort());
        category.setUpdateUserId(userTokenInfoVo.getUserId());
        noticeCategoryMapper.updateByPrimaryKeySelective(category);
        return ServiceResult.ok(categoryId);
    }

    /**
     * 【删除】公告分类，存在绑定关系的则不能删除
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult deleteNoticeCategoryByCategoryId(NoticeCategoryIdReq req) {
        String categoryId = req.getCategoryId();
        NoticeCategory categoryOld = noticeCategoryMapper.selectByPrimaryKey(categoryId);
        if (categoryOld == null) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //判断分类是否存在关联通知公告
        checkRelationNoticeInfo(categoryId);
        //分类删除
        noticeCategoryMapper.deleteByPrimaryKey(categoryId);
        return ServiceResult.ok(categoryId);
    }


    /**
     * 【私有方法，辅助其他接口方法使用】 根据分类id查询是否存在流程项关联
     */
    private void checkRelationNoticeInfo(String categoryId) {
        if (StringUtils.isBlank(categoryId)){
            throw new DuoJuHeException(ErrorCodes.NOTICE_CATEGORY_RELATION_NOTICE_NOT_DELETE);
        }
        Example example = new Example(NoticeInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryId", categoryId);
        if(noticeInfoMapper.selectByExample(example).size()>0){
            throw new DuoJuHeException(ErrorCodes.NOTICE_CATEGORY_RELATION_NOTICE_NOT_DELETE);
        }
    }
}
